﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Jzy.BLL.DocManger;
using Jzy.Core.Common;

using Jzy.Core.Common.Web;
using Jzy.Model.DocManger;

using Frame.Lib.Web;
using Frame.Lib.Core.Right;
using Frame.Lib.Utilities;
using Frame.Lib.Common;
using Frame.Lib.Enums;
using Jzy.DAL;

namespace Jzy.Web.DocManager.Document
{
    public partial class List : PageList
    {      
        private DocumentBO Doc
        {
            get
            {                
                return DocumentBO.Instance<DocumentBO>();
            }
        }

        private string strOrders;

        private string _dirID;
        private string DirID
        {
            get
            {
                if (_dirID == null)
                {
                    if (string.IsNullOrEmpty(Request["DirID"]))
                    {
                        _dirID = (new DirBO()).GetIDByCode(DirCode).ToString();
                    }
                    else
                    {
                        _dirID = StrUtil.DecryptUrl(Request["DirID"]);
                    }
                }
                return _dirID;
            }
        }


        private string DirCode
        {
            get
            {
                return Request["DirCode"];
            }
        }

        private List<int> _canEditDocIDs;//有编辑权限的文档的ID


        private PagerSortSetting _setting;


        protected void Page_Load(object sender, EventArgs e)
        {
            _setting = this.Footer1.InitPager(new BindViewHandler(BindView));

            hidMyDocIDs.Value = ",";

            if (!IsPostBack)
            {
                DirInfo menuInfo = (new DirBO()).GetInfo(DirID);

                switch ((DirType)menuInfo.TypeID)
                {
                    case DirType.图片:
                        Response.Redirect("../picture/PictureList.aspx?DirID=" + StrUtil.EncryptUrl(this.DirID), true);
                        break;
                    case DirType.图片组:
                        Response.Redirect("../picture/GroupList.aspx?DirID=" + StrUtil.EncryptUrl(this.DirID), true);
                        break;
                    case DirType.附件:
                        Response.Redirect("../Attach/List.aspx?DirID=" + StrUtil.EncryptUrl(this.DirID), true);
                        break;
                    case DirType.目录:
                        Response.Redirect("DirList.aspx?DirID=" + this.Encrypt(this.DirID), true);
                        break;
                }

                Pager.BindDrp(drpPager);
                BindView();
                if (DirID != null)
                {
                    lblDirName.Visible = true;
                    lblDirName.Text = (new DirBO()).GetName(DirID) + "&nbsp;";
                }
            }
            AddAttr();
            base.InitSelectID(hidSelectIDs);

           
            strOrders = hidOrders.Value;
            hidOrders.Value = "";

            JSUtil.SetTableHeight("list", 140);

        }


        private void AddAttr()
        {
            JSUtil.DelConfirm(btnDelete, "文章");

            btnMove.Attributes.Add("onclick", "moveDoc('MoveDlg.aspx',document.getElementById('" + hidSelectIDs.ClientID + "'),document.getElementById('" + hidMyDocIDs.ClientID + "'),document.getElementById('" + btnRefresh.ClientID + "'))");


            //判断这个目录有没有增加文档的权限
            RecordRightBO right = new RecordRightBO("DocDirRight");
            List<int> lstBindIDs = right.GetBindIDs(AppSession.UserID, RecordRightName.Add, RightOwnerType.User);
            DirInfo info = (new DirBO()).GetInfo(DirID);

            if (AppSession.UserID == Constants.ADMIN_ID || AppSession.UserID == info.CreatorID || lstBindIDs.Contains(info.ID))
            {
                liAdd.Visible = true;

                string url = "Edit.aspx";
                if (DirID != null)
                {
                    url += "?DirID=" + DirID;
                }
                lnkAdd.HRef = "Edit.aspx?DirID=" + DirID;
            }
            else
            {
                liAdd.Visible = false;
            }
           
            JSUtil.ClickBtn(lnkMove, btnMove);
            JSUtil.ClickBtn(lnkDelete, btnDelete);
            JSUtil.ClickBtn(lnkSaveOrders, btnSaveOrders);

        }

        private void BindView()
        {
            RecordRightBO right = new RecordRightBO(OTableName.DocRight);
            _canEditDocIDs = right.GetBindIDs(AppSession.UserID, RecordRightName.Edit, RightOwnerType.User);

            LVUtil.Init(lv, lvHeader);

            chkSelectAll.Attributes.Add("onclick", "SelectAll(document.getElementById('lvList'))");

            _setting.Input = txtSearch.Text.Trim();

            Pager.SetPageSize(_setting, drpPager);          

            IEnumerable<DocumentInfo>  list = Doc.GetList(int.Parse(DirID), AppSession.UserID, _setting); 

            lblStatistic.Text = "[&nbsp;共<b style='color:red;'> " + _setting.RecordCount + "</b>&nbsp;篇文档&nbsp;]";

            lv.DataSource = list;
            lv.DataKeyNames = new string[] { "ID","CreatorID" };
            lv.DataBind();

           
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (strSelectIDs == "")
            {
                return;
            }
            List<int> lstSelectIDs = StrUtil.SplitToInt(strSelectIDs);

            List<int> lstDisableDeleteIDs = new List<int>();

            if (AppSession.UserID != Constants.ADMIN_ID)
            {
                RecordRightBO right = new RecordRightBO(OTableName.DocRight);
                List<int> lstBindIDs = right.GetBindIDs(AppSession.UserID, RecordRightName.Delete, RightOwnerType.User);
                Dictionary<int, int> ditCreatorIDs = Doc.GetCreatorIDs(lstSelectIDs);
                for (int i = 0; i < lstSelectIDs.Count; i++)
                {
                    int selectID = lstSelectIDs[i];
                    if (ditCreatorIDs.ContainsKey(selectID))
                    {
                        if (ditCreatorIDs[selectID] == AppSession.UserID)
                        {
                            continue;
                        }
                    }
                    if (lstBindIDs.IndexOf(selectID) < 0)
                    {
                        lstDisableDeleteIDs.Add(selectID);
                        lstSelectIDs.RemoveAt(i);
                        i--;
                    }
                }
                if (lstDisableDeleteIDs.Count > 0)
                {
                    List<string> lstDisableDeleteNames = Doc.GetName(lstDisableDeleteIDs);
                    string strDisableDeleteNames = "“" + StrUtil.MergeToStr(lstDisableDeleteNames, "”，“") + "”";
                    string strScript = "alert('" + strDisableDeleteNames + "文档您没权限删除！');";
                    JSUtil.ExcuteJS(strScript);
                }
            }
            //要删除相关的图片和附件
            Doc.Delete(lstSelectIDs);
            BindView();
        }

        protected void btnSaveSequence_Click(object sender, EventArgs e)
        {
            List<int> ids = new List<int>();
            List<int> orders = new List<int>();
            StrUtil.SplitIDOrders(ids, orders, strOrders);
            Doc.SaveOrders(ids, orders);
            BindView();
        }


        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            BindView();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindView();
        }
        protected void drpPager_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindView();
        }


        protected void lv_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                int id = (int)lv.DataKeys[((ListViewDataItem)e.Item).DataItemIndex]["ID"];

                string strID = StrUtil.EncryptUrl(lv.DataKeys[((ListViewDataItem)e.Item).DataItemIndex]["ID"].ToString());
                int creatorID = (int)lv.DataKeys[((ListViewDataItem)e.Item).DataItemIndex]["CreatorID"];

                HyperLink lnkName = (HyperLink)e.Item.FindControl("lnkName");
                lnkName.NavigateUrl = "Detail.aspx?ID=" + strID;


                HyperLink lnkSetRight = (HyperLink)e.Item.FindControl("lnkSetRight");
                lnkSetRight.Style.Add("cursor", "pointer");
                lnkSetRight.Enabled = false;
                if (creatorID == AppSession.UserID || Constants.ADMIN_ID == AppSession.UserID)
                {
                    hidMyDocIDs.Value += id + ",";

                    string url = "SaveDocRight.aspx?DocID=" + strID;
                    lnkSetRight.Enabled = true;

                    JSUtil.ShowForm(lnkSetRight, "设置权限", null, url, 300, 319);
                }


                HyperLink lnkEdit = (HyperLink)e.Item.FindControl("lnkEdit");


                if (creatorID == AppSession.UserID || Constants.ADMIN_ID == AppSession.UserID || _canEditDocIDs.Contains(id))
                {
                    lnkEdit.NavigateUrl = "Edit.aspx?ID=" + strID;
                }
                else
                {
                    lnkEdit.Enabled = false;
                }


                CheckBox chkSelect = (CheckBox)e.Item.FindControl("chkSelect");
                chkSelect.Attributes.Add("onclick", "SetSelectID('" + this.hidSelectIDs.ClientID + "'," + id + ")");
            }
        }
    }
}
